/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.cash.web;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.cash.entity.StoreReserve;
import com.chlitina.store.modules.cash.service.StoreReserveService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.message.entity.StoreEmployeeTask;
import com.chlitina.store.modules.message.service.StoreEmployeeTaskService;
import com.chlitina.store.modules.message.utils.MessageUtils;
import com.chlitina.store.modules.sms.quartz.StoreGroupToCustomerQueueGenerate;
import com.chlitina.store.modules.sms.utils.SmsUtils;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Maps;


/**
 * 预约登记Controller
 * @author lvbo
 * @version 2013-11-05
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/cash/storeReserve")
public class StoreReserveController extends BaseController {

	@Autowired
	private StoreReserveService storeReserveService;
	@Autowired
	private StoreEmployeeTaskService storeEmployeeTaskService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private StoreGroupToCustomerQueueGenerate storeGroupToCustomerQueueGenerate;
	
	@ModelAttribute
	public StoreReserve get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeReserveService.get(id);
		}else{
			return new StoreReserve();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(StoreReserve storeReserve, HttpServletRequest request, HttpServletResponse response, Model model) {
		Store store = StoreUtils.getStore();
		if (store != null){
			storeReserve.setStore(store);
		}
		HttpSession session = request.getSession();
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String oldStart = (String)session.getAttribute("startDate");
		String oldEnd = (String)session.getAttribute("endDate");
		startDate = startDate != null ? startDate : oldStart;
		endDate = endDate != null ? endDate : oldEnd;
        Page<StoreReserve> page = storeReserveService.find(new Page<StoreReserve>(request, response), storeReserve, startDate, endDate); 
        session.setAttribute("startDate", startDate);
		session.setAttribute("endDate", endDate);
        model.addAttribute("page", page);
		return "modules/cash/storeReserveList";
	}

	@RequestMapping(value = "form")
	public String form(StoreReserve storeReserve, Model model) {
		List<Employee> employeeList = employeeService.findByStore(StoreUtils.getStore(), Employee.STATUS_WORKING);
		model.addAttribute("employeeList", employeeList);
		Date requestTime = null;
		if (storeReserve.getId() != null) {
			Customer member = storeReserve.getMember();
			if (member != null) {
				model.addAttribute("isMember", true);
			}
			requestTime = storeReserve.getRequestTime();
			storeReserve.setRequestTime(DateUtils.parseToSqlDateTime(requestTime));
			Date reserveTime = storeReserve.getReserveTime();
			storeReserve.setReserveTime(DateUtils.parseToSqlDateTime(reserveTime));
		} else {
			requestTime = new Date();
		}
		List<Customer> customerList = StoreUtils.getStoreCustomers();
		model.addAttribute("customerList", customerList);
		model.addAttribute("currentDateTime", requestTime);
		model.addAttribute("storeReserve", storeReserve);
		return "modules/cash/storeReserveForm";
	}
	@ResponseBody
	@RequestMapping(value = "detail")
	public String detail(StoreReserve storeReserve, Model model) {
		Map<String, String> map = Maps.newHashMap();
		if (storeReserve != null) {
			if (storeReserve.getMember() !=null) {
				map.put("customerMobile", storeReserve.getMember().getMobile());
				map.put("customerName", storeReserve.getMember().getName());
			} else {
				map.put("customerMobile", storeReserve.getCustomerMobile());
				map.put("customerName", storeReserve.getCustomerName());
			}
			map.put("employeeName", storeReserve.getEmployee().getName());
			map.put("reserveTime", DateUtils.formatDate(storeReserve.getReserveTime(), "yyyy-MM-dd HH:mm"));
			map.put("reason", storeReserve.getReason());
		}
		return JsonMapper.getInstance().toJson(map);
	}

	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, StoreReserve storeReserve, Model model, RedirectAttributes redirectAttributes) {
		Store store = StoreUtils.getStore(true);
		Customer customer = null;
		String customerName=  "";
		String customerMobile=  "";
		String memberId = request.getParameter("memberId");
		String reserveStr = request.getParameter("reserveTime");
		Date reserveTime = DateUtils.parseDate(reserveStr);
		if (memberId != null && !"".equals(memberId)) {
			customer = customerService.get(Long.parseLong(memberId));
			customerName = customer.getName();
			customerMobile = customer.getMobile();
			storeReserve.setMember(customer);
		} else {
			customerName = storeReserve.getCustomerName();
			customerMobile = storeReserve.getCustomerMobile();
		}
		if (reserveTime == null) {
			storeReserve.setReserveTime(new Date());
		}
		storeReserve.setRequestTime(new Date());
		if (storeReserve.getEmployee() != null) {
			Employee employee = employeeService.get(storeReserve.getEmployee().getId());
			storeReserve.setEmployee(employee);
		}
		if (!beanValidator(model, storeReserve)){
			return form(storeReserve, model);
		}
		//生成给客户的短信
		String msg = "尊敬的" + customerName + "先生/女士，您已预约" 
				+ DateUtils.formatDate(storeReserve.getReserveTime() , "yyyy年MM月dd日  HH时") 
				+ "到" + store.getName() + "服务,希望您不要错过预约时间";
		//验证短信剩余条数是否足够
		Calendar cal = SmsUtils.getPlanSendTime(true);
		storeGroupToCustomerQueueGenerate.setPlanSendTime(cal);
		int smsNotified = StoreReserve.SMS_NOT_NOTIFIED;
		boolean systemFlag = storeGroupToCustomerQueueGenerate.volidate();
		int smsNum = storeGroupToCustomerQueueGenerate.getSmsNum(msg.length());
		int remainSmsAmount = store.getSms_remain_amount();
		if (!systemFlag && remainSmsAmount > smsNum) {
			smsNotified = StoreReserve.SMS_NOTIFIED;
		}
		storeGroupToCustomerQueueGenerate.load(store,customerMobile,customer, msg);
		storeGroupToCustomerQueueGenerate.generate();
		//保存预约数据
		storeReserve.setSmsNotified(smsNotified);
		storeReserveService.save(storeReserve);
		//保存员工任务单
		StoreEmployeeTask employeeTask = MessageUtils.transformReserveToEmployeeTask(storeReserve);
		storeEmployeeTaskService.save(employeeTask);
		addMessage(redirectAttributes, "保存预约成功");
		return "redirect:"+Global.ADMIN_PATH+"/cash/storeReserve/list";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		List<StoreEmployeeTask> tasks = storeEmployeeTaskService.findByStoreReserve(id);
		if (tasks != null && tasks.size() > 0) {
			for (StoreEmployeeTask storeEmployeeTask : tasks) {
				if (storeEmployeeTask != null) {
					storeEmployeeTaskService.delete(storeEmployeeTask);
				}
			}
		}
		storeReserveService.delete(id);
		addMessage(redirectAttributes, "删除预约成功");
		return "redirect:"+Global.ADMIN_PATH+"/cash/storeReserve/";
	}

}
